package fr.axones.pocketagile.ui.controler
{
	import flash.events.EventDispatcher;
	
	import fr.axones.pocketagile.ui.components.panel.WaitingPanel;
	
	import mx.collections.ArrayCollection;
	
	import org.spicefactory.lib.reflect.types.Void;
	
	import spark.components.View;
	import spark.components.ViewNavigator;

	[Event(type="fr.axones.pocketagile.ui.controler.ControlerEvent", name="error")]
	[Event(type="fr.axones.pocketagile.ui.controler.ControlerEvent", name="success")]
	public class Controler extends EventDispatcher
	{
		private var listeners:ArrayCollection = new ArrayCollection();
		
		public static var navigator:ViewNavigator;
		
		public function Controler()
		{
		}
		
		public function throwSuccess(message:String, data:*, status:int):void
		{
			var e:ControlerEvent = new ControlerEvent(ControlerEvent.SUCCESS);
			e.message = message;
			e.rawData = data;
			e.status = status;
			dispatchEvent(e);
		}
		
		public function throwError(message:String, data:*, status:int):void
		{
			var e:ControlerEvent = new ControlerEvent(ControlerEvent.ERROR);
			e.message = message;
			e.rawData = data;
			e.status = status;
			dispatchEvent(e);
		}
		
		override public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
		{
			var currentView:View = navigator.activeView; 
			
			if(listeners.length != 0)
			{
				var lastView:View = listeners[0].view as View;
				if(lastView != currentView)
				{
					for each(var o:Object in listeners)
					{
						removeEventListener(o.type, o.listener);
					}
					listeners.removeAll();
				}
			}
			
			listeners.addItem({type:type,listener:listener,view:currentView});
			super.addEventListener(type, listener, useCapture, priority, useWeakReference);	
		}
		
		public function showWaitingPanel():void
		{
			WaitingPanel.show(Controler.navigator.activeView);
		}
		
		public function hideWaitingPanel():void
		{
			WaitingPanel.hide(Controler.navigator.activeView);
		}
	}
}